//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.farm.core.sql.query;

import com.farm.core.auth.util.AuthenticateInter;
import com.farm.core.auth.util.AuthenticateProvider;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.DataResults;
import com.farm.util.spring.HibernateSessionFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class DataQuery {
	static final Logger log = Logger.getLogger(DataQuery.class);
	private static final int CACHE_MAX_SIZE = 5000;
	private int pagesize = 10;
	private boolean isCount = true;
	private String currentPage;
	private String sortTitleText;
	private String sortTypeText;
	private String ruleText;
	private String titles;
	private String tables;
	private String userWhere;
	private DBSort defaultSort;
	private String countSql;
	protected static final Map<String, DataResult> resultCache = new HashMap();
	private boolean DISTINCT = false;
	private long cacheMillisecond;
	protected List<DBSort> sort = new ArrayList();
	protected List<DBRule> queryRule = new ArrayList();

	public DataQuery() {
	}

	public static Map<String, Object> getCacheInfo() {
		Map<String, Object> map = new HashMap();
		map.put("DATAQUERY.CACHE.CURRENT.SIZE", resultCache.size());
		map.put("DATAQUERY.CACHE.MAX.SIZE", Integer.valueOf(5000));
		return map;
	}

	public static void clearCache() {
		resultCache.clear();
	}

	public static DataQuery getInstance(String currentPage, String titles, String tables) {
		DataQuery query = new DataQuery();
		query.setCurrentPage(currentPage);
		query.setTitles(titles);
		query.setTables(tables);
		return query;
	}

	public static DataQuery getInstance(int currentPage, String titles, String tables) {
		return getInstance(String.valueOf(currentPage), titles, tables);
	}

	public DataResult search(Session session) throws SQLException {
		String key = null;
		DataResult result;
		if (this.cacheMillisecond > 0L) {
			key = getQueryMD5Key(this);
			if (key != null) {
				result = (DataResult) resultCache.get(key);
				if (result != null) {
					long time = (new Date()).getTime() - result.getCtime().getTime();
					if (time < this.cacheMillisecond) {
						return result;
					}

					result.setCtime(new Date());
					Searcher search = new Searcher(this);
					Thread searchThread = new Thread(search);
					searchThread.start();
					return result;
				}
			}

			if (resultCache.size() > 5000) {
				resultCache.clear();
			}
		}

		try {
			HibernateQueryHandle.formatSql(session);
		} catch (Exception var9) {
			return DataResult.getInstance();
		}

		if (this.sort.size() <= 0) {
			this.sort.add(this.defaultSort);
		}

		result = null;

		try {
			Searcher search = new Searcher(this);
			result = search.doSearch(session);
			result.setTitles(DataResults.getTitles(this.titles));
			result.setSortTitleText(this.sortTitleText);
			result.setSortTypeText(this.sortTypeText);
		} catch (Exception var8) {
			throw new SQLException(var8);
		}

		if (this.cacheMillisecond > 0L && key != null) {
			result.setCtime(new Date());
			resultCache.put(key, result);
		}

		return result;
	}

	public DataResult search() throws SQLException {
		Session session = HibernateSessionFactory.getSession();
		DataResult result = null;

		try {
			result = this.search(session);
		} finally {
			session.close();
		}

		return result;
	}

	protected static String getQueryMD5Key(DataQuery query) {
		String sql = "";

		try {
			sql = HibernateQueryHandle.praseSQL(query) + ",PAGE:" + query.getCurrentPage();
			AuthenticateInter ai = AuthenticateProvider.getInstance();
			sql = ai.encodeMd5(sql);
			return sql;
		} catch (SQLException var3) {
			log.error(var3 + var3.getMessage());
			return null;
		}
	}

	public DataQuery addSort(DBSort dbsort) {
		this.sort.add(dbsort);
		return this;
	}

	public DataQuery addDefaultSort(DBSort dbsort) {
		this.defaultSort = dbsort;
		return this;
	}

	public DataQuery clearSort() {
		this.sort.clear();
		return this;
	}

	public DataQuery addRule(DBRule rule) {
		DataQuerys.wipeVirus(rule.getValue());
		this.queryRule.add(rule);
		return this;
	}

	public DBRule getAndRemoveRule(int index) {
		DBRule dbrule = (DBRule) this.queryRule.get(index);
		this.queryRule.remove(index);
		this.ruleText = this.parseRules();
		return dbrule;
	}

	public DBRule getAndRemoveRule(String titleName) {
		int n = -1;

		for (int i = 0; i < this.queryRule.size(); ++i) {
			if (((DBRule) this.queryRule.get(i)).getKey().equals(titleName.toUpperCase())) {
				n = i;
			}
		}

		DBRule dbrule = null;
		if (n >= 0) {
			dbrule = this.getAndRemoveRule(n);
		}

		return dbrule;
	}

	private String parseRules() {
		StringBuffer sb = null;
		Iterator var3 = this.queryRule.iterator();

		while (var3.hasNext()) {
			DBRule node = (DBRule) var3.next();
			if (sb == null) {
				sb = new StringBuffer();
			} else {
				sb.append("_,_");
			}

			sb.append(node.getKey());
			sb.append(":");
			sb.append(node.getComparaSign());
			sb.append(":");
			sb.append(node.getValue());
		}

		if (sb == null) {
			return "";
		} else {
			return sb.toString();
		}
	}

	public DataQuery clearRule() {
		this.queryRule.clear();
		return this;
	}

	public DataQuery setDistinct(boolean var) {
		this.DISTINCT = var;
		return this;
	}

	public boolean isDistinct() {
		return this.DISTINCT;
	}

	public int getPagesize() {
		return this.pagesize;
	}

	public DataQuery setPagesize(int pagesize) {
		this.pagesize = pagesize;
		return this;
	}

	public String getCurrentPage() {
		return this.currentPage != null && this.currentPage.trim().length() > 0 ? this.currentPage : "1";
	}

	public DataQuery setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
		return this;
	}

	public DataQuery setCurrentPage(int currentPage) {
		this.currentPage = String.valueOf(currentPage);
		return this;
	}

	public String getSortTitleText() {
		return this.sortTitleText;
	}

	public String getSortTypeText() {
		return this.sortTypeText;
	}

	public void setSortTitleText(String sortTitleText) {
		this.sortTitleText = sortTitleText;
		if (this.sortTitleText != null && this.sortTypeText != null) {
			this.sort.clear();
			this.sort.add(new DBSort(this.sortTitleText, this.sortTypeText));
		}

	}

	public void setSortTypeText(String sortTypeText) {
		if (sortTypeText != null && sortTypeText.toUpperCase().trim().equals("NULL")) {
			sortTypeText = null;
		}

		this.sortTypeText = sortTypeText;
		if (this.sortTitleText != null && this.sortTypeText != null) {
			this.sort.clear();
			this.sort.add(new DBSort(this.sortTitleText, this.sortTypeText));
		}

	}

	public String getRuleText() {
		return this.ruleText;
	}

	public void setRuleText(String ruleText) {
		this.ruleText = ruleText;
		List<DBRule> list = null;
		if (!this.checkStringForLimitDomain(ruleText)) {
			list = new ArrayList();
		} else {
			ruleText = ruleText.replace("_D_", ":");
			String[] strarray = ruleText.split("_,_");
			list = new ArrayList();
			String[] var7 = strarray;
			int var6 = strarray.length;

			for (int var5 = 0; var5 < var6; ++var5) {
				String onestr = var7[var5];
				if (onestr != null && !onestr.trim().equals("")) {
					String[] valueT = onestr.split(":");
					if (valueT.length >= 3 && valueT[0] != null && valueT[1] != null && valueT[2] != null
							&& !valueT[0].equals("") && !valueT[0].equals("") && !valueT[0].equals("")) {
						DBRule dbrule = new DBRule(valueT[0], valueT[2], valueT[1]);
						list.add(dbrule);
					}
				}
			}
		}

		this.queryRule.clear();
		this.queryRule.addAll(list);
	}

	public String getTitles() {
		return this.titles;
	}

	public void setTitles(String titles) {
		this.titles = titles;
	}

	public String getTables() {
		return this.tables;
	}

	public void setTables(String tables) {
		this.tables = tables;
	}

	private boolean checkStringForLimitDomain(String str) {
		return str != null;
	}

	public String getUserWhere() {
		return this.userWhere;
	}

	public void setSqlRule(String sql) {
		this.userWhere = sql;
	}

	public DataQuery addSqlRule(String SQLString) {
		if (this.userWhere == null) {
			this.userWhere = "";
		}

		this.userWhere = this.userWhere + SQLString;
		return this;
	}

	public static DataQuery init(DataQuery query, String tables, String titles) {
		if (query == null) {
			query = new DataQuery();
		}

		query.setTables(tables);
		query.setTitles(titles);
		if (query.sortTypeText == null) {
			query.sortTypeText = "asc";
		}

		if (query.getCurrentPage() == null) {
			query.setCurrentPage("1");
		}

		int n = 0;

		ArrayList indexArray;
		for (indexArray = new ArrayList(); n < query.sort.size(); ++n) {
			if (((DBSort) query.sort.get(n)).getSortTitleText() == null
					|| ((DBSort) query.sort.get(n)).getSortTitleText().trim().toUpperCase().equals("NULL")) {
				indexArray.add(n);
			}
		}

		Iterator var6 = indexArray.iterator();

		while (var6.hasNext()) {
			Integer index = (Integer) var6.next();
			query.sort.remove(index.intValue());
		}

		return query;
	}

	public DBSort getDefaultSort() {
		return this.defaultSort;
	}

	public void setCache(int cachetime, DataQuery.CACHE_UNIT cache_unit) {
		this.cacheMillisecond = (long) (cachetime * cache_unit.num);
	}

	public void setDefaultSort(DBSort defaultSort) {
		this.defaultSort = defaultSort;
	}

	public List<DBRule> getQueryRule() {
		return this.queryRule;
	}

	public void setNoCount() {
		this.isCount = false;
	}

	public boolean isCount() {
		return this.isCount;
	}

	public String getCountSql() {
		return this.countSql;
	}

	public void setCountSql(String countSql) {
		this.countSql = countSql;
	}

	public String getRule(String key) {
		Iterator var3 = this.queryRule.iterator();

		while (var3.hasNext()) {
			DBRule rule = (DBRule) var3.next();
			if (rule.getKey().equals(key)) {
				return rule.getValue();
			}
		}

		return null;
	}

	public static enum CACHE_UNIT {
		Millisecond(1), second(1000), minute(60000);

		public int num;

		private CACHE_UNIT(int val) {
			this.num = val;
		}
	}
}
